package com.dayaokeji.rhythmschoolstudent.client.mine.statistics;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.base.CommonAcitivitMethod;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.course.bean.SemesterBean;
import com.dayaokeji.rhythmschoolstudent.client.mine.statistics.adapter.AttendanceStatisticsAdapter;
import com.dayaokeji.rhythmschoolstudent.utils.CourseUtils;
import com.dayaokeji.rhythmschoolstudent.utils.DateUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.StatisticsApi;
import com.dayaokeji.server_api.domain.StatisticsBean;
import com.dayaokeji.server_api.domain.StatisticsDetailParams;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

public class FindAttendanceStatisticsActivity extends BaseActivity implements CommonAcitivitMethod {

    private static final int START_TIME_FLAG = 1;
    private static final int END_TIME_FLAG = 2;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rv_statistics)
    RecyclerView rvStatistics;
    @BindView(R.id.tv_course_semter)
    TextView tvCourseSemter;

    private static final StatisticsApi statisticsApi = ApiUtils.getApi(StatisticsApi.class);
    private Call<ServerResponse<List<StatisticsBean>>> statisticsCall;
    private final AttendanceStatisticsAdapter attendanceStatisticsAdapter = new AttendanceStatisticsAdapter();

    private String startTime;
    private String endTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_attendance_statistics);
        setSupportActionBar(toolbar);
        init();

    }

    @Override
    public void init() {
        initView();
        initData();
        setOnListener();
    }

    @Override
    public void initView() {
        rvStatistics.setLayoutManager(new LinearLayoutManager(this));
        rvStatistics.setAdapter(attendanceStatisticsAdapter);
        attendanceStatisticsAdapter.setEmptyView(R.layout.empty_layout, rvStatistics);
    }

    @Override
    public void initData() {

    }

    @Override
    public void setOnListener() {
        attendanceStatisticsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                StatisticsBean statisticsBean = (StatisticsBean) adapter.getData().get(position);
                final StatisticsDetailParams statisticsDetailParams = new StatisticsDetailParams(statisticsBean.getCourseId(), startTime, endTime, statisticsBean.getCourseName());
                AttendanceStatisticDetailActivity.Companion.navigation(FindAttendanceStatisticsActivity.this, statisticsDetailParams);
            }
        });
    }

    @OnClick({R.id.ll_choose_semter})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_choose_semter:
                showTimeDialog(START_TIME_FLAG);
                break;
        }
    }

    /**
     * 选择查询学期
     */
    private void showChooseSemester() {
        final List<SemesterBean> semesters = CourseUtils.getSemesters();
        final OptionsPickerView.Builder builder = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int i, int i1, int i2, View view) {
                SemesterBean semesterBean = semesters.get(i);
                if (tvCourseSemter != null) {
                    tvCourseSemter.setText(semesterBean.getSemesterName());
                    tvCourseSemter.setTag(semesterBean.getSemester());
                }

            }
        });
        builder.setTitleText("选择所在学期");
        OptionsPickerView pickerView = builder.build();
        pickerView.setPicker(semesters);
        if (!pickerView.isShowing()) {
            pickerView.show();
        }
    }

    private void showTimeDialog(final int flag) {
        final TimePickerView.Builder builder = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (flag == START_TIME_FLAG) {
                    startTime = DateUtils.format(date,DateUtils.FORMAT_DATE)+" 00:00:00";
                    showTimeDialog(END_TIME_FLAG);
                }else if (flag == END_TIME_FLAG) {
                    endTime = DateUtils.format(date,DateUtils.FORMAT_DATE)+" 23:59:59";
                    tvCourseSemter.setText(" "+startTime+" --- "+endTime);
                    find();
                }
            }
        });
        String title = flag == START_TIME_FLAG ? "选择开始时间" : "选择结束时间";
        builder.setTitleText(title);
        builder.setType(new boolean[]{true, true, true, false, false, false});
        final TimePickerView timePickerView = builder.build();
        timePickerView.setDate(Calendar.getInstance(Locale.CHINA));
        timePickerView.show();
    }

    private void find() {
        if (UserUtils.getUserInfo() == null) {
            ToastUtils.warning("帐号错误");
            return;
        }
        String userId = UserUtils.getUserInfo().getId();
        if (!TextUtils.isEmpty(userId)) {
            HashMap<String, Object> params = new HashMap<>();
            params.put("startTime",startTime);
            params.put("endTime", endTime);
            statisticsCall = statisticsApi.studentStatistics(params);
            statisticsCall.enqueue(new ServerCallback<List<StatisticsBean>>(this,"正在加载...") {
                @Override
                public void onResponse(boolean success, ServerResponse<List<StatisticsBean>> response) {
                    if (success) {
                        if (!FindAttendanceStatisticsActivity.this.isFinishing()) {
                            attendanceStatisticsAdapter.setNewData(response.getBody());
                        }
                    }
                }
            });
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (statisticsCall != null) {
            statisticsCall.cancel();
        }
    }
}
